<template>
  <div class="service-reserve-container">
    <div class="page-header">
      <h1>💆‍♀️ 宠物服务预约</h1>
      <p>为您的爱宠提供专业服务</p>
    </div>

    <!-- 我的预约记录 -->
    <el-card class="my-reserve-card">
      <div slot="header" class="card-header">
        <span>我的预约</span>
        <el-button type="text" @click="showMyReserves = !showMyReserves">
          {{ showMyReserves ? '收起' : '展开' }}
          <i :class="showMyReserves ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
        </el-button>
      </div>
      <el-collapse-transition>
        <div v-show="showMyReserves">
          <el-table :data="myReserves" style="width: 100%" v-loading="loading">
            <el-table-column prop="serviceName" label="服务名称" width="150"></el-table-column>
            <el-table-column prop="reserveDate" label="预约时间" width="180"></el-table-column>
            <el-table-column prop="petName" label="宠物名称" width="120"></el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template slot-scope="scope">
                <el-tag :type="getStatusType(scope.row.status)">{{ scope.row.status }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" @click="handleViewReserve(scope.row)">
                  查看
                </el-button>
                <el-button size="mini" type="danger" @click="handleCancelReserve(scope.row)"
                           v-if="scope.row.status === '待确认'">
                  取消
                </el-button>
              </template>
            </el-table-column>
            <template slot="empty">
              <el-empty description="暂无预约记录"></el-empty>
            </template>
          </el-table>
        </div>
      </el-collapse-transition>
    </el-card>

    <!-- 服务列表 -->
    <div class="service-list">
      <el-row :gutter="20">
        <el-col :span="8" v-for="service in serviceList" :key="service.id">
          <el-card shadow="hover" class="service-card">
            <div class="service-icon">{{ service.icon }}</div>
            <h3>{{ service.name }}</h3>
            <p class="service-desc">{{ service.description }}</p>
            <el-divider></el-divider>
            <el-descriptions :column="1" size="small">
              <el-descriptions-item label="价格">
                <span class="price">¥{{ service.price }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="时长">{{ service.duration }}</el-descriptions-item>
              <el-descriptions-item label="适用">{{ service.suitable }}</el-descriptions-item>
            </el-descriptions>
            <el-button type="success" style="width: 100%; margin-top: 15px;"
                       @click="handleReserve(service)">
              立即预约
            </el-button>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 预约对话框 -->
    <el-dialog title="服务预约" :visible.sync="reserveDialogVisible" width="600px">
      <el-form :model="reserveForm" :rules="reserveRules" ref="reserveForm" label-width="100px">
        <el-form-item label="服务名称">
          <el-input v-model="reserveForm.serviceName" disabled></el-input>
        </el-form-item>
        <el-form-item label="选择宠物" prop="petId">
          <el-select v-model="reserveForm.petId" placeholder="请选择宠物" style="width: 100%">
            <el-option v-for="pet in myPets" :key="pet.id" :label="pet.name" :value="pet.id">
              <span>{{ pet.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ pet.breed }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预约日期" prop="reserveDate">
          <el-date-picker
            v-model="reserveForm.reserveDate"
            type="datetime"
            placeholder="选择日期时间"
            style="width: 100%"
            :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="reserveForm.phone" placeholder="请输入联系电话"></el-input>
        </el-form-item>
        <el-form-item label="备注说明">
          <el-input type="textarea" v-model="reserveForm.remark"
                    :rows="3" placeholder="请输入备注说明"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="reserveDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitReserve">确认预约</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getServiceList, getMyServiceReserves, createServiceReserve, cancelServiceReserve } from '@/api/service'
import { getMyPets } from '@/api/user'

export default {
  name: 'ServiceReserve',
  data () {
    return {
      loading: false,
      showMyReserves: false,
      myReserves: [],
      serviceList: [],
      myPets: [],
      reserveDialogVisible: false,
      reserveForm: {
        serviceId: null,
        serviceName: '',
        petId: null,
        reserveDate: '',
        phone: '',
        remark: ''
      },
      reserveRules: {
        petId: [{ required: true, message: '请选择宠物', trigger: 'change' }],
        reserveDate: [{ required: true, message: '请选择预约时间', trigger: 'change' }],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ]
      },
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      }
    }
  },
  created () {
    // 先加载服务列表和宠物列表，然后再加载预约数据
    Promise.all([
      this.loadServiceList(),
      this.loadMyPets()
    ]).then(() => {
      // 确保服务列表和宠物列表加载完成后再加载预约数据
      this.loadMyReserves()
    }).catch(err => {
      console.error('初始化数据加载失败：', err)
      // 即使失败也尝试加载预约数据
      this.loadMyReserves()
    })
  },
  methods: {
    loadServiceList () {
      this.loading = true
      return getServiceList({
        pageNum: 1,
        pageSize: 100
      }).then(res => {
        this.loading = false
        if (res && res.data) {
          const data = res.data.records || res.data.list || res.data || []
          this.serviceList = data.map(item => ({
            id: item.id,
            name: item.name || item.serviceName,
            icon: this.getServiceIcon(item.name || item.serviceName),
            description: item.description || '',
            price: item.price || 0,
            duration: item.duration || '1小时',
            suitable: item.suitable || '所有宠物'
          }))
        }
        return Promise.resolve()
      }).catch(err => {
        this.loading = false
        console.error('加载服务列表失败：', err)
        this.$message.error({ message: '加载服务列表失败', duration: 800 })
        return Promise.reject(err)
      })
    },
    loadMyReserves () {
      this.loading = true
      getMyServiceReserves({
        pageNum: 1,
        pageSize: 100
      }).then(res => {
        this.loading = false
        if (res && res.data) {
          const data = res.data.records || res.data.list || res.data || []
          console.log('我的预约原始数据：', data) // 调试日志
          this.myReserves = data.map(item => {
            // 处理后端返回的字段（可能是下划线或驼峰命名）
            const serviceTypeId = item.serviceTypeId || item.service_type_id
            const petId = item.petId || item.pet_id
            const reservationDate = item.reservationDate || item.reservation_date
            const reservationTime = item.reservationTime || item.reservation_time
            const reservationStatus = item.reservationStatus !== undefined ? item.reservationStatus : (item.reservation_status !== undefined ? item.reservation_status : item.status)
            
            // 从服务列表中查找服务名称
            let serviceName = item.serviceName || item.name || ''
            if (!serviceName && serviceTypeId) {
              const service = this.serviceList.find(s => s.id === serviceTypeId)
              serviceName = service ? service.name : '未知服务'
            }
            
            // 从宠物列表中查找宠物名称
            let petName = item.petName || ''
            if (!petName && petId) {
              const pet = this.myPets.find(p => p.id === petId)
              petName = pet ? pet.name : '未知宠物'
            }
            
            // 组合日期和时间
            let reserveDate = reservationDate || ''
            if (reservationDate && reservationTime) {
              reserveDate = `${reservationDate} ${reservationTime}`
            } else if (reservationDate) {
              reserveDate = reservationDate
            } else if (reservationTime) {
              reserveDate = reservationTime
            }
            
            return {
              id: item.id,
              serviceName: serviceName || '未知服务',
              reserveDate: reserveDate || '',
              petName: petName || '未知宠物',
              status: this.getStatusText(reservationStatus)
            }
          })
          console.log('处理后的预约数据：', this.myReserves) // 调试日志
          // 如果有数据，默认展开
          if (this.myReserves.length > 0) {
            this.showMyReserves = true
          }
        }
      }).catch(err => {
        this.loading = false
        console.error('加载我的预约失败：', err)
        this.$message.error({ message: '加载我的预约失败', duration: 800 })
      })
    },
    loadMyPets () {
      return getMyPets().then(res => {
        if (res && res.data) {
          const data = res.data.list || res.data || []
          this.myPets = data.map(item => ({
            id: item.id,
            name: item.name || item.petName,
            breed: item.breed || ''
          }))
        }
        return Promise.resolve()
      }).catch(err => {
        console.error('加载我的宠物失败：', err)
        return Promise.reject(err)
      })
    },
    getServiceIcon (name) {
      const iconMap = {
        '洗澡': '🛁',
        '美容': '✂️',
        '训练': '🎓',
        '体检': '🩺',
        '按摩': '💆',
        '牙齿': '🦷',
        '护理': '💆'
      }
      for (const key in iconMap) {
        if (name.includes(key)) {
          return iconMap[key]
        }
      }
      return '🛁'
    },
    getStatusText (status) {
      const statusMap = {
        0: '待确认',
        1: '已确认',
        2: '已完成',
        3: '已取消'
      }
      return statusMap[status] || '待确认'
    },
    handleReserve (service) {
      this.reserveForm = {
        serviceId: service.id,
        serviceName: service.name,
        petId: null,
        reserveDate: '',
        phone: '',
        remark: ''
      }
      this.reserveDialogVisible = true
    },
    submitReserve () {
      this.$refs.reserveForm.validate((valid) => {
        if (valid) {
          const reserveDate = new Date(this.reserveForm.reserveDate)
          const dateStr = reserveDate.toISOString().split('T')[0]
          const timeStr = reserveDate.toTimeString().split(' ')[0]
          // 确保时间格式为 HH:mm:ss
          const timeStrFormatted = timeStr.length === 5 ? timeStr + ':00' : timeStr
          createServiceReserve({
            serviceTypeId: this.reserveForm.serviceId,
            petId: this.reserveForm.petId,
            reservationDate: dateStr,
            reservationTime: timeStrFormatted,
            remarks: this.reserveForm.remark || ''
          }).then(res => {
            this.$message.success({ message: '预约成功！', duration: 800 })
            this.reserveDialogVisible = false
            this.loadMyReserves()
          }).catch(err => {
            console.error('预约失败：', err)
            this.$message.error({ message: err.message || '预约失败', duration: 800 })
          })
        }
      })
    },
    handleViewReserve (row) {
      this.$alert(`
        <p><strong>服务：</strong>${row.serviceName}</p>
        <p><strong>时间：</strong>${row.reserveDate}</p>
        <p><strong>宠物：</strong>${row.petName}</p>
        <p><strong>状态：</strong>${row.status}</p>
      `, '预约详情', {
        dangerouslyUseHTMLString: true
      })
    },
    handleCancelReserve (row) {
      this.$confirm('确认取消该预约吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        cancelServiceReserve(row.id).then(res => {
          this.$message.success({ message: '已取消预约', duration: 800 })
          this.loadMyReserves()
        }).catch(err => {
          console.error('取消预约失败：', err)
          this.$message.error({ message: '取消预约失败', duration: 800 })
        })
      })
    },
    getStatusType (status) {
      const typeMap = {
        '待确认': 'warning',
        '已确认': 'primary',
        '已完成': 'success',
        '已取消': 'info'
      }
      return typeMap[status] || 'info'
    }
  }
}
</script>

<style scoped>
.service-reserve-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
  padding: 30px;
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
  color: white;
  border-radius: 8px;
}

.page-header h1 {
  margin: 0 0 10px 0;
  font-size: 32px;
}

.my-reserve-card {
  margin-bottom: 30px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.service-list {
  margin-bottom: 20px;
}

.service-card {
  text-align: center;
  margin-bottom: 20px;
  height: 100%;
  transition: all 0.3s;
}

.service-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.service-icon {
  font-size: 64px;
  margin-bottom: 15px;
}

.service-card h3 {
  margin: 0 0 10px 0;
  font-size: 20px;
  color: #333;
}

.service-desc {
  color: #666;
  font-size: 14px;
  margin-bottom: 15px;
  min-height: 40px;
}

.price {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
}
</style>
